package com.zrb.mobile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zrb.mobile.adapter.model.RegisterDto;
import com.zrb.mobile.adapter.model.UserDtos;
import com.zrb.mobile.adapter.model.UserbaseinfoDtos;
import com.zrb.mobile.common.LoadUserAvatar;
 
import com.zrb.mobile.ui.CenterProgressWebView;
import com.zrb.applib.utils.AppSetting;
import com.zrb.mobile.utility.CommonUtil;
import com.zrb.mobile.utility.ProgressDialogEx;
import com.zrb.mobile.utility.Tip;
import com.zrb.mobile.utility.ZrbRestClient;

public class Project_surveyActivity extends BaseActivity implements OnClickListener {

 
    int  projectId;//aotuId
    Button submitBtn;
    EditText  mlooktime;
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm"); //:ss
    Tip progTip;
    EditText mlookperson;
    EditText mcontactphone;
    EditText mlookpersonnum;
	ProgressBar toploading;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);

 		setContentView(R.layout.project_survey);
 		if (bundle != null)
			restoreSelf(bundle);
		else {
			projectId=this.getIntent().getIntExtra("projectId", -1);
		}
  		initView();
  		LoadUserinfo();
	}
	
	@Override
	protected  void onSaveInstanceState(Bundle outState)
    {
       super.onSaveInstanceState(outState);
       outState.putInt("projectId", projectId);
   }

   private void restoreSelf(Bundle savedInstanceState)
   {
	   projectId = savedInstanceState.getInt("projectId", -1); 
   } 

   private void LoadUserinfo() {
		if(AppSetting.curUser==null) return;
		String url = String.format("user/doUserInfo?zrb_front_ut=%1$s", AppSetting.curUser.zrb_front_ut);
	 
		toploading.setVisibility(View.VISIBLE);
	    ZrbRestClient.get(url, null, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 				toploading.setVisibility(View.GONE);
 			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
  				toploading.setVisibility(View.GONE);
				String results = new String(arg2);
 	 			try {
					Gson gson =new Gson();
	 				UserbaseinfoDtos tmpDto=gson.fromJson(results, UserbaseinfoDtos.class);
	 				if(tmpDto.res==1){
	 					mcontactphone.setText(tmpDto.data.uMobile);
 	 				}
 				} catch (Exception e) {
					// loadingview.HideText(e.getMessage()).ShowRefleshBtn(true).ShowError();
				}
 			}
		});
	}
   
	private void initView() {
	 
		View lefticon= this.findViewById(R.id.title_left_root);
		lefticon.setOnClickListener(this);
		
		toploading=(ProgressBar)this.findViewById(R.id.topbar_loading);
		
		this.findViewById(R.id.looktime_btn_choose).setOnClickListener(this);
		
		TextView txtTitle=	(TextView)this.findViewById(R.id.txt_title);
		txtTitle.setText("ԤԼ��Ŀ����");
		
		mlooktime=	(EditText)this.findViewById(R.id.edit_looktime);
		mlooktime.setText(dateformat.format(new Date()));
		
		mlookperson=	(EditText)this.findViewById(R.id.edit_lookperson);
		mcontactphone=	(EditText)this.findViewById(R.id.edit_contactphone);
		mcontactphone.addTextChangedListener(phonechange);
		
		mlookpersonnum=	(EditText)this.findViewById(R.id.edit_lookpersonnum);
 		
		if(AppSetting.curUser!=null){
			mlookperson.setText(AppSetting.curUser.uname);
 		}
 		
		submitBtn=(Button)this.findViewById(R.id.login_btn);
		submitBtn.setOnClickListener(this);
 	}
 	
	TextWatcher phonechange= new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if( s.length() != 0 && null != mcontactphone.getText() && !"".equals(mcontactphone.getText().toString())){
				boolean flag=CommonUtil.isMobileNO(mcontactphone.getText().toString());
				submitBtn.setEnabled(flag);
 			}else{
				submitBtn.setEnabled(false);
  			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			
		}
	};
	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.title_left_root:
			this.finish();
			break;
		case R.id.login_btn:
			user_submit();
			break;	
		case R.id.looktime_btn_choose:
			 Intent it = new Intent(this, Date_pickerActivity.class);
			 this.startActivityForResult(it, 100);//time
			break;
 		}
 	}
	
	private void showloading() {
		if (progTip == null)
			progTip = ProgressDialogEx.Show(this, " title", "�����ύ��...", true,
					true);
		else
			progTip.Show("�����ύ��...");
	}
	
	private void user_submit() {
		if(AppSetting.curUser==null){
 		  CommonUtil.showToast("�û�δ��½", Project_surveyActivity.this);
 		  return;
		}
		/*if(AppSetting.curUser.userType.equals("2")) //gov
		{	
			CommonUtil.showToast("��ǰ����ǹ���Ա�����ܽ��п���", Project_surveyActivity.this);
			Project_surveyActivity.this.finish();
		   return;
		}*/
		String name = this.mlookperson.getText().toString();
		 String personnum = this.mlookpersonnum.getText().toString();
 		if (TextUtils.isEmpty(name)) {
			CommonUtil.showToast("�����˲���Ϊ��", Project_surveyActivity.this);
			return;
		}
		if (TextUtils.isEmpty(personnum)) {
			CommonUtil.showToast("������Ϊ��", Project_surveyActivity.this);
			return;
			
		}
		
		if(projectId==-1) {
			CommonUtil.showToast("��Ŀid����ȷ", Project_surveyActivity.this);
			return;
		}
		
		 showloading();
		 RequestParams param = new RequestParams();
		 param.put("inspectTime", mlooktime.getText().toString().replace("/", "-")+":00");
		 param.put("projectId", projectId);
		 param.put("personNum", personnum);
		 param.put("telphone", mcontactphone.getText().toString());
		 param.put("contact", name);
		 param.put("companyName",  AppSetting.curUser.org);
 		 param.put("zrb_front_ut", AppSetting.curUser.zrb_front_ut);
 		 
 		 
 		// CommonUtil.InfoLog("user_submit", param.toString());
		 ///inspect/userInspectApply?inspectTime=2015-08-01 00:00:00&projectId=300&personNum=4&telphone=15972920600&contact=ricky&companyName=ibm&zrb_front_ut=27e527e6a5e22013d98dffa4f6eee266
  		 ZrbRestClient.post("inspect/userInspectApply" , param,
						new AsyncHttpResponseHandler() {

							@Override
							public void onFailure(int arg0, Header[] arg1, byte[] arg2,
									Throwable arg3) {
								// TODO Auto-generated method stub
								progTip.Dismiss();
 								CommonUtil.showToast("���糬ʱ,����������", Project_surveyActivity.this);
							}

							@Override
							public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
								// TODO Auto-generated method stub
								progTip.Dismiss();
								String results = new String(arg2);
								//Log.e("tag", results);{"res":1,"msg":null,"data":7,"bannerData":null}
								CommonUtil.InfoLog("userInspectApply", results);
 								try {
									Gson gson = new Gson();
									RegisterDto tmpDto = gson.fromJson(results,RegisterDto.class);
									if(tmpDto.res==1){
										CommonUtil.showToast("ԤԼ��Ŀ����ɹ�", Project_surveyActivity.this); 
										 new Handler().postDelayed(new Runnable() {
						                        @Override
						                        public void run() {
						                        	Project_surveyActivity.this.finish();
					 	                        }
						                }, 2000);
  	 								}else{
  	 									CommonUtil.showToast(tmpDto.msg, Project_surveyActivity.this); 
  								   }
 							} catch (Exception e) {

									CommonUtil.showToast( "fail:"+e.getMessage(),Project_surveyActivity.this);
									System.out.println("eeee!!!!" + e.getMessage());

								}

							}
						});
 	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

	         if (resultCode == android.app.Activity.RESULT_OK) {
	            switch (requestCode) {
	             case 100://tv_instruction
	                String curvalue3=data.getStringExtra("time");
	                mlooktime.setText(curvalue3.replace("-", "/"));
	               break;
	            }
	             super.onActivityResult(requestCode, resultCode, data);
	        }
	    }

}
